﻿
using System ;
using System.IO ;

using MskEdit.Dxf.Model ;


namespace MskEdit.Dxf.Backend
{

    public static class DxfDocumentReader
    {
        public static DxfDocument TryRead( FileInfo dxfFileInfo, DxfDocument fallbackValue ) {
                     
            if ( ! dxfFileInfo.Exists )
                return fallbackValue ;
                
            if ( string.IsNullOrEmpty( dxfFileInfo.Extension ) )
                return fallbackValue ;
                
            if ( ! dxfFileInfo.Extension.ToLower().Equals( ".dxf" ) )
                return fallbackValue ;

            string [] allLines = File.ReadAllLines( dxfFileInfo.FullName ) ;
            for ( int i = 0 ; i < allLines.Length ; ++i ) {
                allLines[i] = allLines[i].Trim() ;
            }
            
            string documentName = dxfFileInfo.Name.Substring( 0, dxfFileInfo.Name.Length - 4 ) ;
            
            DxfDocument dxfDocument = DxfDocument.TryFrom( documentName, allLines, null ) ;
            if ( dxfDocument == null )
                return fallbackValue ;
/*            
            while ( internalLineNo < allLines.Length ) {
            
                DxfSection dxfSection = DxfSectionReader.TryRead( allLines, ref internalLineNo, null ) ;
                if ( dxfSection != null ) {
                    lineNo = internalLineNo ;
                    dxfDocument.AddSection( dxfSection ) ;
                    continue ;
                }
                
                // Nothing found. Creep forward
                internalLineNo += 1 ;
            }
*/
            return dxfDocument ;                 
        }

    }
}
